package handler

import (
	"demo/model"
	"demo/resource"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

// Index _
func Index(ctx *gin.Context) {
	log.Println("handling index")
	mysql := resource.GetDB()
	user, err := model.GetUser(mysql, 1)
	if err != nil {
		log.Fatalf("get user error: %v", err)
	}

	ctx.String(200, "table list: %v", user.Name)
}

type Person struct {
	ID   int64  `json:"id"`
	Name string `json:"title"`
}

func Res(ctx *gin.Context) {
	log.Println("res handler")
	p := Person{1, "sasukexun"}
	ctx.JSON(200, p)
}

// Download _
func Download(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello download"))
	return
}

func Add(ctx *gin.Context) {
	var u model.User
	err := ctx.ShouldBindQuery(&u)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"message": "struct binding error"})
		return
	}

	if u.Name == "" {
		ctx.JSON(http.StatusInternalServerError, gin.H{"message": "missing name"})
		return
	}

	mysql := resource.GetDB()
	err = model.AddUser(mysql, &u)
	if err != nil {
		ctx.String(http.StatusInternalServerError, "error")
	} else {
		ctx.String(http.StatusOK, "succeed")
	}
}

func Update(ctx *gin.Context) {
	var u model.User
	err := ctx.ShouldBindQuery(&u)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"message": "missing id or name"})
		return
	}

	if u.Name == "" || u.ID == 0 {
		ctx.JSON(http.StatusInternalServerError, gin.H{"message": "missing id or name"})
	}

	mysql := resource.GetDB()
	err = model.UpdateUser(mysql, &u)
	if err != nil {
		ctx.String(http.StatusInternalServerError, "error")
	} else {
		ctx.String(http.StatusOK, "succeed")
	}
}
